import React, { useEffect, useRef, useState } from 'react'
import Swiper from '../HomeModel/Swiper'
import {
    StyleSheet,
    Text,
    View,
    Pressable,
    ScrollView,
    Image,
    Dimensions,
    TextInput,
    Animated,
    VirtualizedList
} from 'react-native'
import AsyncStorage from '@react-native-async-storage/async-storage'
import { LinearGradient } from 'expo-linear-gradient';
import axios from 'axios';
import { useRouter, Link, useFocusEffect } from 'expo-router';

export default function home() {

    const router = useRouter();

    const fadeAnim = useRef(new Animated.Value(0)).current

    const opacity = fadeAnim.interpolate({
        inputRange: [0, 100], // 滚动距离范围
        outputRange: [0, 1],  // 对应的透明度范围
        extrapolate: 'clamp', // 超出范围时保持最后一个值
    });


    const handleScroll = (event: any) => {
        fadeAnim.setValue(event.nativeEvent.contentOffset.y);
    }

    useEffect(() => {
        getlist()
    }, [])

    const [list, setlist] = useState([])
    const [a, seta] = useState('')
    const getlist = async () => {
        await axios.get('http://192.168.13.227:3000/lzl/getList').then(res => {
            // console.log(res.data)
            setlist(res.data);
        })
    }
    const replaceCommasWithPipes = (str: String) => {
        return str.replace(/，/g, ' | ');
    };
    const handleLocalstory = async (item: any) => {
        router.push('/DescPage')
        AsyncStorage.setItem('shopInfo', JSON.stringify(item))
    }
    const renderItem = ({ item }: any) => (
        <Pressable key={item._id} style={styles.rxshopcar} onPress={() => (handleLocalstory(item))}>
            <Image
                style={[styles.rxshopimg]}
                source={{ uri: item.img[0] }}
            />
            <View style={{ padding: 10 }}>
                <Text>{item.name}</Text>
                <Text style={{ fontSize: 12, marginTop: 5, color: "#aeaeae", lineHeight: 25 }}>{replaceCommasWithPipes(item.description)}</Text>
                <Text style={{ fontSize: 18, marginTop: 5, color: 'red', lineHeight: 25 }}>
                    <Text style={{ fontSize: 12 }}>￥</Text>
                    {item.price}
                </Text>
            </View>
        </Pressable>
    );


    return (
        <ScrollView
            stickyHeaderIndices={[0]}
            style={{ height: "100%", backgroundColor: '#faffef', }}
            onScroll={handleScroll}
            scrollEventThrottle={16} // 控制滚动事件的频率
        >


                <View style={styles.stickyHeader}>
                    <Animated.View style={[styles.box, { opacity }]}></Animated.View>
                    <View style={styles.Input}>
                        <TextInput
                            onFocus={() => (
                                router.push('/HomeModel/Search')
                            )}
                            style={styles.search}
                            placeholder='精选天然水果'
                            inlineImageLeft='search_icon'
                            value={a}
                        />
                    </View>
                </View>

                <View>
                    <Swiper></Swiper>
                </View>


            <View>
                <View style={[styles.navigation]}>
                    <Pressable onPress={() => (router.push('/cate'))}>
                        <LinearGradient
                            colors={['#ff1110', '#fc887f']}
                            start={[1, 1]}
                            end={[0, 0]}
                            style={styles.tuijian}
                        >
                            <Image source={require("@/assets/img/推荐.png")} />
                        </LinearGradient>

                        <Text style={styles.navigation_text}>推荐</Text>
                    </Pressable>
                    <Pressable onPress={() => (router.push('/cate'))}>
                        <LinearGradient
                            colors={['#14d013', '#9cec95']}
                            start={[1, 1]}
                            end={[0, 0]}
                            style={styles.tuijian}
                        >
                            <Image source={require("@/assets/img/水果类.png")} />
                        </LinearGradient>
                        <Text style={styles.navigation_text}>水果类</Text>
                    </Pressable>
                    <Pressable onPress={() => (router.push('/cate'))}>
                        <LinearGradient
                            colors={['#39d273', '#63fac2']}
                            start={[1, 1]}
                            end={[0, 0]}
                            style={styles.tuijian}
                        >
                            <Image source={require("@/assets/img/蔬菜类.png")} />
                        </LinearGradient>
                        <Text style={styles.navigation_text}>蔬菜类</Text>
                    </Pressable>
                    <Pressable onPress={() => (router.push('/cate'))}>
                        <LinearGradient
                            colors={['#ffa113', '#fccf7f']}
                            start={[1, 1]}
                            end={[0, 0]}
                            style={styles.tuijian}
                        >
                            <Image source={require("@/assets/img/干果类.png")} />
                        </LinearGradient>
                        <Text style={styles.navigation_text}>干果类</Text>
                    </Pressable>
                    <Pressable onPress={() => (router.push('/cate'))}>
                        <LinearGradient
                            colors={['#ffcf46', '#fce6aa']}
                            start={[1, 1]}
                            end={[0, 0]}
                            style={styles.tuijian}
                        >
                            <Image source={require("@/assets/img/油粮类.png")} />
                        </LinearGradient>
                        <Text style={styles.navigation_text}>油粮类</Text>
                    </Pressable>
                </View>

                <View>
                    <LinearGradient
                        colors={['#fd5e5b', '#ffc386']}
                        start={[0, 0]}
                        end={[1, 0]}
                        style={styles.huodong}
                    >
                        <Text
                            style={{
                                fontSize: 18,
                                fontWeight: "bold",
                                color: "#fff"
                            }}>
                            有奖邀请活动火热进行中...
                        </Text>
                        <Text
                            style={{
                                fontSize: 12,
                                color: "#fff",
                                marginTop: 5

                            }}>
                            活动日期:10.12-10.26
                        </Text>
                    </LinearGradient>
                </View>

                <View style={[styles.container, { marginTop: 20 }]}>
                    {/* 最新上架 */}
                    <View style={{ marginTop: 20 }}>
                        <View style={{ width: 310, borderWidth: 1, borderColor: "#99cc33" }}></View>
                        <Text style={styles.textcenter}>最新上架</Text>
                    </View>
                    {/* 最新上架  列表*/}
                    <View style={[styles.Itemflex]}>
                        {
                            list.filter((item: any) => item.category === "最新上架").map((item: any) => (
                                <Pressable style={styles.shopcar} key={item._id} onPress={() => (handleLocalstory(item))}>
                                    {/* <View style={styles.shopcar} > */}
                                    <Image
                                        style={[styles.shopimg]}
                                        source={{ uri: item.img[0] }}
                                    />
                                    <View style={{ padding: 10 }}>
                                        <Text>{item.name}</Text>
                                        <Text style={{ fontSize: 12, marginTop: 5, color: "#aeaeae" }}>{replaceCommasWithPipes(item.description)}</Text>
                                        <Text style={{ fontSize: 18, marginTop: 5, color: 'red' }}>
                                            <Text style={{ fontSize: 12 }}>￥</Text>
                                            {item.price}
                                        </Text>
                                    </View>

                                    {/* </View> */}
                                </Pressable>
                            ))
                        }
                    </View>

                    {/* 热销产品 */}
                    <View style={{ marginTop: 20 }}>
                        <View style={{ width: 310, borderWidth: 1, borderColor: "#99cc33" }}></View>
                        <Text style={styles.textcenter}>热销商品</Text>
                    </View>

                    {/* 热销产品 列表*/}
                    <View style={[styles.rxItemflex]}>
                        {
                            list.filter((item: any) => item.category === "热销商品").map((item: any) => (
                                <Pressable key={item._id} style={styles.rxshopcar} onPress={() => (handleLocalstory(item))}>
                                    <Image
                                        style={[styles.rxshopimg]}
                                        source={{ uri: item.img[0] }}
                                    />
                                    <View style={{ padding: 10 }}>
                                        <Text>{item.name}</Text>
                                        <Text style={{ fontSize: 12, marginTop: 5, color: "#aeaeae", lineHeight: 25 }}>{replaceCommasWithPipes(item.description)}</Text>
                                        <Text style={{ fontSize: 18, marginTop: 5, color: 'red', lineHeight: 25 }}>
                                            <Text style={{ fontSize: 12 }}>￥</Text>
                                            {item.price}
                                        </Text>
                                    </View>
                                </Pressable>
                            ))
                        }
                    </View>

                    {/* 更多推荐 */}
                    <View style={{ marginTop: 20 }}>
                        <View style={{ width: 310, borderWidth: 1, borderColor: "#99cc33" }}></View>
                        <Text style={styles.textcenter}>更多推荐</Text>
                    </View>
                    {/* 更多推荐 列表*/}
                    <View style={[styles.rxItemflex]}>
                        {/* <VirtualizedList
                            // contentContainerStyle={[styles.virtualizedList]}
                            data={list}
                            initialNumToRender={10}
                            renderItem={renderItem}
                            keyExtractor={(item: any) => item._id}
                            getItemCount={() => list.length}
                            getItem={(data: any, index: any) => data[index]}
                        /> */}
                        {
                            list.map((item: any) => (
                                <Pressable key={item._id} style={styles.rxshopcar} onPress={() => (handleLocalstory(item))}>
                                    <Image
                                        style={[styles.rxshopimg]}
                                        source={{ uri: item.img[0] }}
                                    />
                                    <View style={{ padding: 10 }}>
                                        <Text>{item.name}</Text>
                                        <Text style={{ fontSize: 12, marginTop: 5, color: "#aeaeae", lineHeight: 25 }}>{replaceCommasWithPipes(item.description)}</Text>
                                        <Text style={{ fontSize: 18, marginTop: 5, color: 'red', lineHeight: 25 }}>
                                            <Text style={{ fontSize: 12 }}>￥</Text>
                                            {item.price}
                                        </Text>
                                    </View>
                                </Pressable>
                            ))
                        }
                    </View>
                </View>
            </View>

        </ScrollView>
    )
}

const styles = StyleSheet.create({
    container: {
        justifyContent: 'center',
        alignItems: 'center',
    },
    search: {
        width: Dimensions.get('window').width - Dimensions.get('window').width / 2.5,
        margin: 15,
        borderWidth: 0,
        borderColor: '#ccc',
        paddingHorizontal: 10,
        borderRadius: 50,
        backgroundColor: '#fff',
        color: "#d7dad9",
    },
    navigation: {
        flexDirection: 'row',
        justifyContent: "space-evenly",
        alignItems: 'center',
        backgroundColor: '#faffef',
        padding: 10
    },
    tuijian: {
        width: 50,
        height: 50,
        borderRadius: 13,
        flexDirection: 'row',
        justifyContent: 'center',
        alignItems: 'center'
    },
    navigation_text: {
        fontSize: 12,
        textAlign: "center"
    },
    Input: {
        // position: 'absolute',
        // top: 2
    },
    huodong: {
        width: 310,
        marginLeft: 25,
        marginTop: 10,
        height: 70,
        borderRadius: 10,
        backgroundColor: '#fff',
        justifyContent: 'center',
        padding: 10,
    },
    textcenter: {
        fontSize: 18,
        position: "relative",
        alignSelf: 'center', // 自动居中对齐
        top: "-50%",
        backgroundColor: "#faffef",
        width: 100,
        textAlign: "center"
    },
    Itemflex: {
        display: 'flex',
        flexWrap: 'wrap',
        width: 310,
        flexDirection: 'row',
        justifyContent: 'space-between',
    },
    shopcar: {
        width: 150,
        marginTop: 10,
        backgroundColor: '#fff',
        borderRadius: 10,
    },
    shopimg: {
        width: 150,
        height: 100,
        borderTopLeftRadius: 10,
        borderTopRightRadius: 10
    },
    rxItemflex: {
        display: 'flex',
        width: 310,
        marginTop: 10
    },
    rxshopcar: {
        width: 310,
        height: 100,
        marginTop: 5,
        marginBottom: 5,
        display: "flex",
        flexDirection: "row",
        backgroundColor: '#fff',
        borderRadius: 10,
    },
    rxshopimg: {
        width: 100,
        height: 100,
        borderRadius: 10
    },
    box: {
        position: "absolute",
        width: Dimensions.get('window').width,
        height: 50,
        backgroundColor: "rgb(153,204,51)",
        justifyContent: 'center',
        alignItems: 'center',
    },
    stickyHeader: {
        position: "absolute",
        backgroundColor:'rgb(182,243,126)',
        top: 0,
        left: 0,
        right: 0,
        zIndex: 1000,
        height: 50,
    },
})